package util;


import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.rmi.ServerException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * 滑动图片验证码工具类
 *
 * maven 依赖：
 *     <dependency>
 *         <groupId>javax.media</groupId>
 *         <artifactId>jai_core</artifactId>
 *         <version>1.1.3</version>
 *     </dependency>
 *
 *
 */
public class SliderCaptchaUtil {

    private static final int GAP_WIDTH = 60;
    private static final int GAP_HEIGHT = 60;

    private static MinioClient minioClient = MinioClient.builder()
            .endpoint("http://192.168.7.40:9000/")
            .credentials("VxyqHWUl9DaBX4as1fzZ", "Nyg7KKfbRT0VTaQHRRYaJvjKhaMmUMvGcruXjMm6")
            .build();

    // 从 MinIO 下载图片
    public static BufferedImage downloadImageFromMinio(String bucketName, String objectName) throws  InsufficientDataException, ErrorResponseException, IOException,  io.minio.errors.ServerException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        try (GetObjectResponse response = minioClient.getObject(getObjectArgs)) {
            return ImageIO.read(response);
        }
    }

    // 上传图片到 MinIO
    public static void uploadImageToMinio(BufferedImage image, String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, io.minio.errors.ServerException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        byte[] imageBytes = outputStream.toByteArray();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);

        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(inputStream, imageBytes.length, -1)
                .contentType("image/png")
                .build();
        minioClient.putObject(putObjectArgs);
    }

    // 生成滑动验证码相关信息
    public static CaptchaInfo generateCaptcha(String bucketName, String backgroundObjectName, String targetObjectName, String gapObjectName) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, io.minio.errors.ServerException {
        // 从 MinIO 下载背景图片
        BufferedImage backgroundImage = downloadImageFromMinio(bucketName, backgroundObjectName);
        int width = backgroundImage.getWidth();
        int height = backgroundImage.getHeight();

        // 随机生成缺口位置
        Random random = new Random();
        int x = random.nextInt(width - GAP_WIDTH);
        int y = random.nextInt(height - GAP_HEIGHT);

        // 创建缺口图片
        BufferedImage gapImage = new BufferedImage(GAP_WIDTH, GAP_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = gapImage.createGraphics();
        g2d.drawImage(backgroundImage, 0, 0, GAP_WIDTH, GAP_HEIGHT, x, y, x + GAP_WIDTH, y + GAP_HEIGHT, null);
        g2d.dispose();

        // 在背景图片上移除缺口部分
        Graphics2D bgG2d = backgroundImage.createGraphics();
        bgG2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
        bgG2d.fillRect(x, y, GAP_WIDTH, GAP_HEIGHT);
        bgG2d.dispose();

        // 上传处理后的图片到 MinIO
        uploadImageToMinio(backgroundImage, bucketName, targetObjectName);
        uploadImageToMinio(gapImage, bucketName, gapObjectName);

        return new CaptchaInfo(x, y);
    }

    // 验证码信息类
    public static class CaptchaInfo {
        private final int x;
        private final int y;

        public CaptchaInfo(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y;
        }
    }
}